
using System;
using System.IO;
using EnvDTE;
using UnitLite.Util;

namespace UnitLite.Util
{
    /// <summary>
    /// This class is used to create/load target test file of project.
    /// </summary>
	public class DocumentLoader
	{
        /// <summary>
        /// If document is existed, load the document;otherwise, create the document by template.
        /// </summary>
        /// <param name="project"></param>
        /// <param name="FullName"></param>
        /// <returns></returns>
		public Document Load(Project project, string FullName)
		{
			Document doc = null;

			try
			{

                if (project.ProjectItems == null || project.ProjectItems.Count == 0)
                {
                    throw new NullReferenceException("No project existed.");
                }

                if (String.IsNullOrEmpty(FullName))
                {
                    throw new NullReferenceException("File Name is empty");
                }

     
				ProjectItem item = null;

				if (File.Exists(FullName))
				{
					item = LoadFromLocal(project.ProjectItems, FullName);
				}
				else
				{
					item = LoadFromTemplate(project.ProjectItems, FullName);
				}

				doc = item.Open(Constants.vsViewKindCode).Document;
				doc.Activate();
			}
			catch (System.Exception ex)
			{
				Console.WriteLine(ex.Message);
			}

			return doc;
		}	

		internal ProjectItem LoadFromLocal(ProjectItems items, string FullName)
		{			   
			ProjectItem item = FindProjectItem(items, FullName);
			
			if (item == null)
			{
				item = items.AddFromFile(FullName);
			}
			
			return item;
		}

		internal ProjectItem LoadFromTemplate(ProjectItems items, string FullName)
		{
            return items.AddFromTemplate(ProjectSettings.FilePath, Path.GetFileName(FullName));
		}

		internal ProjectItem FindProjectItem(ProjectItems items, string Name)
		{
			return items.DTE.Solution.FindProjectItem(Name);
		}
	}
}
